package com.dq.usercenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dq.commonutils.jwt.JwtUtil;
import com.dq.commonutils.pojo.DqException;
import com.dq.usercenter.entity.UcenterMember;
import com.dq.usercenter.service.UcenterMemberService;
import com.dq.usercenter.mapper.UcenterMemberMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dq.usercenter.vo.UserMemberVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * 会员表(UcenterMember)表服务实现类
 *
 * @author Dq
 * @since 2022-08-07 17:18:43
 */
@Slf4j
@Service
public class UcenterMemberServiceImpl  extends ServiceImpl<UcenterMemberMapper, UcenterMember>  implements UcenterMemberService {
    private static final String SECRET="Dq333";

    @Autowired
    private UcenterMemberMapper userMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @Override
    public String loginUser(UserMemberVo userMemberVo) {
        /**
         * 1. 获取用户手机号
         * 2. 校验数据合法性
         * 3. 根据数据查询 校验手机号 密码  用户权限
         * 4. 存入token
         */
        String mobile = userMemberVo.getMobile();
        String password = userMemberVo.getPassword();
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)){
            throw new DqException(20001,"登录失败");
        }

        //判断手机号是否正确
        LambdaQueryWrapper<UcenterMember> ucenterMemberLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ucenterMemberLambdaQueryWrapper
                .eq(UcenterMember::getMobile,mobile)
                .select(
                        UcenterMember::getId,
                        UcenterMember::getMobile,
                        UcenterMember::getPassword,
                        UcenterMember::getIsDisabled,
                        UcenterMember::getNickname,
                        UcenterMember::getAvatar

                );
        UcenterMember user = userMapper.selectOne(ucenterMemberLambdaQueryWrapper);
        if (user==null){
            throw new DqException(20001,"登录失败");
        }
        //加盐校验  f8d8c25d4b9dd50a1de8af7f40554754  f8d8c25d4b9dd50a1de8af7f40554754
        String passwordToCheck = DigestUtils.md5Hex(password + SECRET);
        System.out.println(passwordToCheck);
        if (!user.getPassword().equals(passwordToCheck)){
            throw new DqException(20001,"登陆失败");
        }

        if (user.getIsDisabled() == 1){
            throw new DqException(20001,"用户已被管理员拉黑，请联系管理人员重新解开。");
        }



        //校验成功生成一个token
        String token = JwtUtil.createToken(user.getId(), user.getNickname());
        //存入缓存
        UserMemberVo userVo = new UserMemberVo();
        BeanUtils.copyProperties(user,userVo);
        userVo.setPassword(null);
        String userInfoForJson = JSON.toJSONString(userVo);
        log.info("----------------------------");
        log.info("存入的缓存token={}   :   value = {}  ","TOKEN-"+token,userInfoForJson);
        redisTemplate.opsForValue().set("TOKEN-"+token,userInfoForJson,1, TimeUnit.DAYS);
        log.info("----------------------------");

        return token;
    }

    @Override
    public String register(UserMemberVo userMemberVo) {
        /**
         * 1. 获取Vo数据
         * 2. 判断验证码是否正确 因为在发短信的时候把验证码存入的redis中 只需要比对你传入的code就OK
         * 3. 判断手机号是否重复（selectCount）
         * 4. 最后添加
         * 5. 查询当前用户并存入redis 然后返回token
         */
        String code = userMemberVo.getCode();
        String mobile = userMemberVo.getMobile();
        String password = userMemberVo.getPassword();
        String nickname = userMemberVo.getNickname();
        if (StringUtils.isEmpty(code) || StringUtils.isEmpty(mobile)
                || StringUtils.isEmpty(password) || StringUtils.isEmpty(nickname) ){
            throw new DqException(20001,"注册失败");
        }

        //判断验证码
        String redisCode = redisTemplate.opsForValue().get(userMemberVo.getMobile());
        if (! redisCode.equals(userMemberVo.getCode())){
            throw new DqException(20003,"验证码错误");
        }

        //判断手机号是否存在
        LambdaQueryWrapper<UcenterMember> ucenterMemberLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ucenterMemberLambdaQueryWrapper.eq(UcenterMember::getMobile,userMemberVo.getMobile());
        Integer selectCount = userMapper.selectCount(ucenterMemberLambdaQueryWrapper);
        if (selectCount>=1){
            throw new DqException(20002,"手机号已存在");
        }
        //校验完毕 开始添加用户
        UcenterMember ucenterMember = new UcenterMember();
        BeanUtils.copyProperties(userMemberVo,ucenterMember);
        String passWordMd5 = DigestUtils.md5Hex(userMemberVo.getPassword() + SECRET);
        ucenterMember.setPassword(passWordMd5);
        ucenterMember.setAvatar("https://guli-dq-1310347558.cos.ap-chengdu.myqcloud.com/guli/2022/07/21/518876f1399842d6838efb7a4876c0a0.png");
        userMapper.insert(ucenterMember);

        //查询用户 封装VO对象存入Redis
        LambdaQueryWrapper<UcenterMember> memberLambdaQueryWrapper = new LambdaQueryWrapper<>();
        memberLambdaQueryWrapper
                .eq(UcenterMember::getMobile,userMemberVo.getMobile())
                .eq(UcenterMember::getPassword,passWordMd5)
                .select(
                        UcenterMember::getMobile,
                        UcenterMember::getId,
                        UcenterMember::getNickname,
                        UcenterMember::getAvatar)
                .last("limit 1");
        UcenterMember user = userMapper.selectOne(memberLambdaQueryWrapper);
        String token = JwtUtil.createToken(user.getId(), user.getNickname());
        UserMemberVo userVo = new UserMemberVo();
        BeanUtils.copyProperties(user,userVo);
        String userInfoForJson = JSON.toJSONString(userVo);
        log.info("-----------------------------");
        log.info("用户走了注册接口");
        log.info("token为{}",token);
        log.info("userInfo为{}",userInfoForJson);
        redisTemplate.opsForValue().set("TOKEN-"+token,userInfoForJson,1, TimeUnit.DAYS);
        log.info("-----------------------------");
        return token;
    }

    //退出
    @Override
    public void logout(String token) {

        if (StringUtils.isEmpty(token)){
            throw new DqException(20001,"token异常");
        }
        redisTemplate.delete("TOKEN-"+token);
    }

    //查询用户openid
    @Override
    public UcenterMember getOpenidMember(String openid) {
        LambdaQueryWrapper<UcenterMember> ucenterMemberLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ucenterMemberLambdaQueryWrapper.eq(UcenterMember::getOpenid,openid);
        UcenterMember ucenterMember = userMapper.selectOne(ucenterMemberLambdaQueryWrapper);
        return ucenterMember;
    }

    /*public static void main(String[] args) {
        String password= DigestUtils.md5Hex("123456" + SECRET);
        System.out.println(password);
    }*/
}